<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { View, Hide } from '@element-plus/icons-vue'
import TopNav from './navmenu.vue'
import db from '../../utils/database.js'

const formData = ref({
  compressPassword: '',
  confirmPassword: ''
})
const showCompressPassword = ref(false)
const showConfirmPassword = ref(false)

// 计算属性：检查两次密码是否一致
const isPasswordValid = computed(() => {
  return formData.value.compressPassword && 
         formData.value.confirmPassword &&
         formData.value.compressPassword === formData.value.confirmPassword
})

// 实时校验密码
const validatePassword = () => {
  if (formData.value.compressPassword && formData.value.confirmPassword) {
    if (formData.value.compressPassword !== formData.value.confirmPassword) {
      ElMessage.error('两次输入的密码不一致，请重新输入')
    }
  }
}

// 获取当前用户名
const getCurrentUsername = async () => {
  try {
    const sessionId = localStorage.getItem('sessionId')
    if (!sessionId) {
      throw new Error('未找到会话ID')
    }
    
    const sessionResult = await window.electronAPI.invoke('auth-verify-session', { sessionId })
    if (!sessionResult.success || !sessionResult.isAuthenticated) {
      throw new Error('会话验证失败')
    }
    
    return sessionResult.username
  } catch (error) {
    console.error('获取用户名失败:', error)
    throw error
  }
}

const handleBackup = async () => {
  if (!formData.value.compressPassword) {
    ElMessage.warning('请输入压缩密码')
    return
  }
  if (formData.value.compressPassword !== formData.value.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  try {
    // 获取当前用户名
    const username = await getCurrentUsername()
    
    // 获取当前用户的备份路径
    const userResult = await db.query(
      'SELECT backup FROM users WHERE LOWER(username) = LOWER(?)', 
      [username]
    )
    
    let backupPath = ''
    if (userResult.length > 0 && userResult[0].backup) {
      backupPath = userResult[0].backup
    } else {
      // 如果用户没有设置备份路径，使用IPC调用获取项目根目录
      const projectPathResult = await window.electronAPI.invoke('get-project-path')
      if (!projectPathResult.success) {
        throw new Error('获取项目路径失败')
      }
      backupPath = `${projectPathResult.path}/data/backup`
    }

    // 调用IPC API执行备份操作
    const result = await window.electronAPI.invoke('perform-backup', {
      backupPath,
      password: formData.value.compressPassword
    })

    if (result.success) {
      ElMessage.success(`数据备份成功，已保存到: ${backupPath}`)
    } else {
      throw new Error(result.error || '备份失败')
    }
  } catch (error) {
    console.error('备份失败:', error)
    ElMessage.error(`备份失败: ${error.message}`)
  }
}

const handleRestore = async () => {
  if (!formData.value.compressPassword) {
    ElMessage.warning('请输入压缩密码')
    return
  }

  try {
    // 获取当前用户名
    const username = await getCurrentUsername()
    
    // 获取当前用户的备份路径
    const userResult = await db.query(
      'SELECT backup FROM users WHERE LOWER(username) = LOWER(?)', 
      [username]
    )
    
    let backupPath = ''
    if (userResult.length > 0 && userResult[0].backup) {
      backupPath = userResult[0].backup
    } else {
      // 如果用户没有设置备份路径，使用IPC调用获取项目根目录
      const projectPathResult = await window.electronAPI.invoke('get-project-path')
      if (!projectPathResult.success) {
        throw new Error('获取项目路径失败')
      }
      backupPath = `${projectPathResult.path}/data/backup`
    }
    
    const resultTem = await window.electronAPI.invoke('perform-preRestoreBackUp', {
      backupPath,
      password: formData.value.compressPassword
    })



    // 调用IPC API执行还原操作
    const result = await window.electronAPI.invoke('perform-restore', {
      backupPath,
      password: formData.value.compressPassword
    })

    if (result.success) {
      ElMessage.success(`数据还原成功`)
    } else {
      throw new Error(result.error || '还原失败')
    }
  } catch (error) {
    console.error('还原失败:', error)
    ElMessage.error(`还原失败: ${error.message}`)
  }
}
</script>

<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 内容区域用 Card 包裹 -->
    <div class="content-wrapper">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>数据备份与还原</span>
          </div>
        </template>

        <!-- 主要内容 -->
        <div class="main-content">
          <div class="password-form">
            <div class="form-group">
              <label class="form-label">密码</label>
              <el-input 
                v-model="formData.compressPassword"
                placeholder="请输入数据包压缩密码" 
                :type="showCompressPassword ? 'text' : 'password'"
                class="password-input"
              >
                <template #suffix>
                  <el-icon 
                    class="password-toggle" 
                    @click="showCompressPassword = !showCompressPassword"
                  >
                    <View v-if="showCompressPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </div>
            <div class="form-group">
              <label class="form-label">确认密码</label>
              <el-input 
                v-model="formData.confirmPassword"
                placeholder="请确认数据包压缩密码" 
                :type="showConfirmPassword ? 'text' : 'password'"
                class="password-input"
                @blur="validatePassword"
              >
                <template #suffix>
                  <el-icon 
                    class="password-toggle" 
                    @click="showConfirmPassword = !showConfirmPassword"
                  >
                    <View v-if="showConfirmPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 警告提示 -->
          <div class="warning-tip">
            <span class="warning-icon">⚠</span>
            <span class="warning-text">
              注意：数据备份和还原功能仅适用于当前版本软件。
            </span>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button 
              type="primary" 
              class="backup-btn" 
              @click="handleBackup"
              :disabled="!isPasswordValid"
            >
              <span class="btn-icon">📁</span>
              数据备份
            </el-button>
            <el-button 
              type="primary" 
              class="restore-btn" 
              @click="handleRestore"
              :disabled="!isPasswordValid"
            >
              <span class="btn-icon">↻</span>
              数据还原
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 98vh;
  background: #f5f6f8;
}

.content-wrapper {
  flex: 1;
  padding: 10px;
  overflow: hidden;
}

.card-header {
  font-size: 22px;
  font-weight: bold;
}

.box-card {
  height: 100%;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  padding: 20px;
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10% 20px;
}

.password-form {
  width: 100%;
  max-width: 700px;
  margin-bottom: 20px;
}

.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.form-label {
  width: 80px;
  text-align: right;
  color: #333;
  margin-right: 15px;
  font-size: 16px;
}

.password-input {
  flex: 1;
}

.password-toggle {
  cursor: pointer;
  color: #909399;
  transition: color 0.3s;
}

.password-toggle:hover {
  color: #409eff;
}

:deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
}

:deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.warning-tip {
  background: #fef0f0;
  border: 1px solid #fde2e2;
  border-radius: 6px;
  padding: 5px;
  margin-bottom: 20px;
  width: 100%;
  max-width: 600px;
  text-align: center;
}

.warning-icon {
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.warning-text {
  color: #f56c6c;
  font-size: 15px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.backup-btn,
.restore-btn {
  background: #20B2AA;
  border: none;
  padding: 12px 24px;
  height: auto;
}

.backup-btn:hover,
.restore-btn:hover {
  background: #1a9c96;
}


.btn-icon {
  margin-right: 8px;
  font-size: 16px;
}
</style>